package com.wangxiaonan.wxwork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.domain.MessageTemplate;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.AgentService;
import com.wangxiaonan.wxwork.service.MessageService;
import com.wangxiaonan.wxwork.service.MessageTemplateService;
import com.wangxiaonan.wxwork.service.TaskService;
import com.wangxiaonan.wxwork.service.TokenService;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class TaskServiceImpl implements TaskService {

    private static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Resource
    private TokenService tokenService;
    @Resource
    private AgentService agentService;
    @Resource
    private MessageService messageService;
    @Resource
    private MessageTemplateService messageTemplateService;

    @Override
    @Retryable(value = {ServiceException.class})
    public String dailyTask(Map<String, Object> param) {
        if (CollectionUtils.isEmpty(param)) {
            throw new NullPointerException("param_invalid");
        }
        String agentId = (String) param.get("agent_id");
        Integer templateId = (Integer) param.get("template_id");
        if (StringUtils.isBlank(agentId) || templateId == null) {
            throw new NullPointerException("param_invalid");
        }
        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            throw new ServiceException("no_result", "agent not exists");
        }
        MessageTemplate messageTemplate = messageTemplateService.getById(templateId);
        if (messageTemplate == null) {
            throw new ServiceException("no_result", "messageTemplate not exists");
        }

        // 获取数据，填充template

        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException e) {
            logger.error("[TaskServiceImpl] dailyTask >>> get token fail ", e);
            throw new NullPointerException("token invalid");
        }
        logger.info("[TaskServiceImpl] dailyTask >>> agent_id: {}, template_id: {}", agentId, templateId);
        JSONObject jsonObject = messageService.sendMessage(token, messageTemplate.getTemplate());

        return jsonObject.toJSONString();
    }

    @Recover
    public String recover(ServiceException se, Map<String, Object> param) {
        logger.error("[TaskServiceImpl] recover {} ", se.getCode(), se);
        throw new ServiceException(se.getCode(), se.getMsg());
    }
}
